package com.mvu.banana.common.widget;

import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.mvu.banana.common.client.CommonConstants;
import com.mvu.banana.common.client.GlobalResources;

/**
 */
public class HintListener implements FocusHandler, BlurHandler {
  private static HintListener INSTANCE;
  private HintPopup hintPopup;

  public static HintListener get() {
    if (INSTANCE == null) {
      INSTANCE = new HintListener();
    }
    return INSTANCE;
  }

  private HintListener() {
  }

  public void onFocus(FocusEvent focusEvent) {
    Element element = focusEvent.getRelativeElement();
    int bottom = element.getAbsoluteBottom();
    if (hintPopup == null) {
      hintPopup = new HintPopup();
    }
    hintPopup.setMessage(CommonConstants.get.getString(element.getTitle()));
    hintPopup.setWidth("10em");
    hintPopup.setPopupPosition(element.getAbsoluteRight() + 3, element.getAbsoluteTop() - 5);
    hintPopup.show();
  }

  public void onBlur(BlurEvent event) {
    if (hintPopup != null) {
      hintPopup.hide();
    }
  }

  class HintPopup extends PopupPanel {
    @UiField
    Label message;

    public HintPopup() {
      super(true);
      message = new Label();
      setWidget(message);
      setStyleName(GlobalResources.get.css().hintPopup());
    }

    public void setMessage(String message) {
      this.message.setText(message);
    }
  }
}
